package xcmg.device.service.barcode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.barcode.BarcodeManageDO;
import xcmg.device.dao.mapper.BarcodeManageMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.JsonUtil;
import xcmg.device.infra.enums.BarcodeStatus;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.vo.barcode.SinglePrintDetailVO;
import xcmg.device.service.vo.barcode.SinglePrintVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:WangKe
 * @Description:
 * @Date：Created in 9:12 2019/1/5 0005
 */
@Service
public class BarcodeBatchPrintService {

    @Autowired
    private BarcodeManageMapper barcodeManageMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private HttpServletResponse response;

//    @Value("${barcode.prefix.url}")
//    private String barcodePrefixUrl;

    public void directPrintExportBatch(String materialsNo, BigDecimal totalQty, Integer totalSize, String detailListStr, String userId, String orgId) throws Exception {
        LogHelper.monitor("===参数====" + materialsNo + "==" + totalQty+ "==" + totalSize+ "==" + detailListStr+ "==" + userId+ detailListStr+ "==" + orgId);
        totalSize = totalSize == null ? 1 : (totalSize > 10000 ? 10000 : totalSize);
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (priMaterialsDO == null) {
            throw new Exception("零件编码不存在");
        }

        List<BarcodeManageDO> list = new ArrayList<>();
        ActionResult<List<String>> totalResult = fastGenClient.batchText(totalSize+1);
        if (totalResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("异常");
        }
        List<String> totalList=totalResult.getValue();
        int materialsCount=JsonUtil.jsonToList(detailListStr, SinglePrintDetailVO[].class).size();
        int barCount=materialsCount * totalSize;
        if(barCount>100000){
            throw new Exception("打印数据超过十万");
        }
        ActionResult<List<String>> bartextResult = fastGenClient.batchText(barCount+totalSize);
        if (bartextResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("异常");
        }
        List<String> barcodeList=bartextResult.getValue();
        LogHelper.monitor("===start====" + materialsNo + "========" + totalSize);
        for (int n = 0; n < totalSize; n++) {
            SinglePrintVO singlePrintVO = new SinglePrintVO();
            singlePrintVO.setMaterialsNo(materialsNo);
            singlePrintVO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
            singlePrintVO.setTotalQty(totalQty);
            singlePrintVO.setDetailList(JsonUtil.jsonToList(detailListStr, SinglePrintDetailVO[].class));
            List<BarcodeManageDO> doList;
            String barcode=totalList.get(n);
            List<String>curBarcodes=barcodeList.subList(n*materialsCount,(n+1)*materialsCount);
            try {
                doList = this.singleDirectPrint(singlePrintVO, userId, orgId,barcode,curBarcodes);
                list.addAll(doList);
            } catch (Exception e) {
                LogHelper.monitor(e.getMessage());
            }
        }

        insert(list);

        LogHelper.monitor("===end====" + materialsNo + "========" + totalSize);

        String title = "直投条码导出-" + materialsNo;
        String[] rowsName = new String[]{"序号", "条码", "总条码", "条码标识", "单据编号",
                "VIN码", "图号", "零件编码", "零件名称", "总条码的总数量", "当前条码数量", "条码状态"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            BarcodeManageDO exportDO = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] =   exportDO.getBarcode();
            objs[2] = exportDO.getTotalBarcode();
            objs[3] = exportDO.getBarcodeFlag() == 0 ? "总条码" : "分条码";
            objs[4] = exportDO.getBillNo();
            objs[5] = exportDO.getVinid();
            objs[6] = exportDO.getOrawyd();
            objs[7] = exportDO.getMaterialsNo();
            objs[8] = exportDO.getMaterialsDes();
            objs[9] = exportDO.getTotalQty();
            objs[10] = exportDO.getCurrentQty();
            objs[11] = exportDO.getStatusDesc();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private void insert(List<BarcodeManageDO> list) {
        if (!ListUtil.isNullOrEmpty(list)) {
            int size = 1000;
            LogHelper.monitor("========直投批量生成条码新增开始========" + list.size());
            int times = list.size() / size;
            int ot = list.size() % size;
            for (int i = 0; i < times; i++) {
                barcodeManageMapper.batchInsert(list.subList(i * size, (i + 1) * size));
            }
            if (ot > 0) {
                barcodeManageMapper.batchInsert(list.subList(times * size, list.size()));
            }
            LogHelper.monitor("========直投批量生成条码新增结束========");
        }
    }

    public List<BarcodeManageDO> singleDirectPrint(SinglePrintVO singlePrintVO, String userId, String orgId,String totalBarcode,List<String> curBarcodes) throws Exception {
//        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(singlePrintVO.getMaterialsNo(), orgId);
//        if (priMaterialsDO == null) {
//            throw new Exception("零件编码不存在");
//        }
//        singlePrintVO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
        singlePrintVO.setBillNo(genDocumentService.getDocumentNo(BillDesc.DirectBill));
//        ActionResult<String> textResult = fastGenClient.textGuid();
//        if (textResult.getCode() != ErrorCode.Success.getCode()) {
//            singlePrintVO.setErrorCode(ErrorCode.IllegalArument);
//            return new ArrayList<>();
//        }
//        String totalBarcode = textResult.getValue();
        String userName = "";
        List<BarcodeManageDO> results = new ArrayList<>();
//        BarcodeManageVO barcodeManageVO = new BarcodeManageVO();
        singlePrintVO.setRowNo(null);
        BarcodeManageDO barcodeManageDO = makeTotalSingleBarcode(singlePrintVO, totalBarcode, orgId, userId, userName);
//        barcodeManageMapper.insert(barcodeManageDO);
//        BeanUtils.copyProperties(barcodeManageDO, barcodeManageVO);
        results.add(barcodeManageDO);
        int i = 0;
//        ActionResult<List<String>> bartextResult = fastGenClient.batchText(singlePrintVO.getDetailList().size()+1);
//        if (bartextResult.getCode() != ErrorCode.Success.getCode()) {
//            throw new Exception("异常");
//        }
        List<String> barcodeList=curBarcodes;
        for (SinglePrintDetailVO detailVO : singlePrintVO.getDetailList()) {
            if (detailVO.getCurrentQty().equals(0)) {
                continue;
            }
            String barcode = barcodeList.get(i);
            i++;
//            BarcodeManageVO subBarcodeManageVO = new BarcodeManageVO();
            BarcodeManageDO subBarcodeManageDO = makeSubSingleBarcode(singlePrintVO, detailVO, barcode, totalBarcode, orgId, userId, userName, i, 1);
//            barcodeManageMapper.insert(subBarcodeManageDO);
//            BeanUtils.copyProperties(subBarcodeManageDO, subBarcodeManageVO);
            results.add(subBarcodeManageDO);
        }
        singlePrintVO.setErrorCode(ErrorCode.Success);
        for (BarcodeManageDO result : results) {
            result.setChildCount(i);
        }
        return results;
    }

    private BarcodeManageDO makeTotalSingleBarcode(SinglePrintVO singlePrintVO, String totalBarcode, String orgId, String userId, String userName) {
        BarcodeManageDO barcodeManageDO = new BarcodeManageDO();
        barcodeManageDO.setBarcode(totalBarcode);
        barcodeManageDO.setTotalBarcode(totalBarcode);
        barcodeManageDO.setOrgId(orgId);
        barcodeManageDO.setBillType(singlePrintVO.getBillType());
        barcodeManageDO.setBillId(singlePrintVO.getBillId());
        barcodeManageDO.setBillNo(singlePrintVO.getBillNo());
        barcodeManageDO.setBarcodeFlag(0);
        barcodeManageDO.setMaterialsNo(singlePrintVO.getMaterialsNo());
        barcodeManageDO.setMaterialsDes(singlePrintVO.getMaterialsDes());
        barcodeManageDO.setTotalQty(singlePrintVO.getTotalQty());
        barcodeManageDO.setCurrentQty(singlePrintVO.getTotalQty());
        barcodeManageDO.setLeftQty(singlePrintVO.getLeftQty());
        barcodeManageDO.setWarehouseCode(singlePrintVO.getWarehouseCode());
        barcodeManageDO.setPrintId(userId);
        barcodeManageDO.setPrintName(userName);
        barcodeManageDO.setReprintCount(0);
        barcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        barcodeManageDO.setRowNo(singlePrintVO.getRowNo());
        if ("2".equals(barcodeManageDO.getBarcodeStatus())) {
            barcodeManageDO.setStatusDesc("已出库");
        } else {
            barcodeManageDO.setStatusDesc("已打印");
        }
        barcodeManageDO.setCreateId(userId);
        barcodeManageDO.setCreateName(userName);
        barcodeManageDO.setIsDel(false);
        barcodeManageDO.setIsSeparate(false);
        barcodeManageDO.setSeq(0);
        return barcodeManageDO;
    }

    private BarcodeManageDO makeSubSingleBarcode(SinglePrintVO singlePrintVO, SinglePrintDetailVO detailVO, String barcode, String totalBarcode, String orgId, String userId, String userName, Integer seq, int type) {
        BarcodeManageDO subBarcodeManageDO = new BarcodeManageDO();
        subBarcodeManageDO.setBarcode(barcode);
        subBarcodeManageDO.setTotalBarcode(totalBarcode);
        subBarcodeManageDO.setOrgId(orgId);
        subBarcodeManageDO.setBillType(singlePrintVO.getBillType());
        subBarcodeManageDO.setBillNo(singlePrintVO.getBillNo());
        subBarcodeManageDO.setBillId(singlePrintVO.getBillId());
        subBarcodeManageDO.setBarcodeFlag(1);
        subBarcodeManageDO.setBarcodeDesc(detailVO.getBarcodeDesc());
        subBarcodeManageDO.setVinid(detailVO.getVinid());
        subBarcodeManageDO.setOrawyd(detailVO.getOrawyd());
        subBarcodeManageDO.setMaterialsNo(singlePrintVO.getMaterialsNo());
        subBarcodeManageDO.setMaterialsDes(singlePrintVO.getMaterialsDes());
        subBarcodeManageDO.setTotalQty(singlePrintVO.getTotalQty());
        subBarcodeManageDO.setCurrentQty(detailVO.getCurrentQty());
        subBarcodeManageDO.setLeftQty(singlePrintVO.getLeftQty());
        subBarcodeManageDO.setWarehouseCode(singlePrintVO.getWarehouseCode());
        subBarcodeManageDO.setPrintId(userId);
        subBarcodeManageDO.setPrintName(userName);
        subBarcodeManageDO.setReprintCount(0);
        subBarcodeManageDO.setModel(detailVO.getModel());
        subBarcodeManageDO.setRowNo(singlePrintVO.getRowNo());
        if (type == 1) {
            subBarcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.OutStorage.toString());
        } else {
            subBarcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        }
        if ("2".equals(subBarcodeManageDO.getBarcodeStatus())) {
            subBarcodeManageDO.setStatusDesc("已出库");
        } else {
            subBarcodeManageDO.setStatusDesc("已打印");
        }
        subBarcodeManageDO.setCreateId(userId);
        subBarcodeManageDO.setCreateName(userName);
        subBarcodeManageDO.setRemark(detailVO.getRemark());
        subBarcodeManageDO.setIsDel(false);
        subBarcodeManageDO.setIsSeparate(false);
        subBarcodeManageDO.setSeq(seq);
        return subBarcodeManageDO;
    }
}
